<?php

/**
 * Usuario
 *  
 * @author Tiago Santos
 * @version 
 */

class Usuario {
	private $table;
	
	public function getDbTable(){
		if($this->table === NULL){
			require_once APPLICATION_PATH . '/models/DbTable/Usuario.php';
			$this->table = new UsuarioDbTable();
		}
		return $this->table;
	}
	
	public function getAll(){
		$dt = $this->getDbTable();
		$select = $dt->select()->order('ds_nome');
		$rows = $dt->fetchAll($select)->toArray();
		return $rows;
	}
	
	public function getByEmailSenha($login,$senha){
		$dt = $this->getDbTable();
		$select = $dt->select()
			->where("ds_login = '" . $login . "'")
			->where("ds_senha = '" . sha1($senha.STRHASH) . "'");
		$rows = $dt->fetchAll($select);
		$rows = $rows->toArray();
		if(count($rows) > 0)
			return $rows[0];
		else return array();
	}
	
	/*public function getByEmail($email){
		$dt = $this->getDbTable();
		$select = $dt->select()->where('ds_email = ' . $email);
		$rows = $dt->fetchAll($select);
		$rows = $rows->toArray();
		return $rows[0];
	}
	
	public function getById($codigo){
		$dt = $this->getDbTable();
		$select = $dt->select()->where('cd_cliente = ' . $codigo);
		$rows = $dt->fetchAll($select);
		$rows = $rows->toArray();
		return $rows[0];
	}*/
	
	public function save($array){
		unset($array['ds_senha_confirmacao']);
		if(trim($array['ds_senha'])=='')
			unset($array['ds_senha']);
		else
			$array['ds_senha'] = sha1($array['ds_senha'].STRHASH);
		
		if(trim($array['cd_cliente'])!=''){
			$this->update($array,"cd_cliente = " . $array['cd_cliente']);
		}else{
			unset($array['cd_cliente']);
			$this->getDbTable()->insert($array);
		}
	}
	
	public function update($array,$where){
		$this->getDbTable()->update($array,$where);
	}
	
	public function delete($where){
		$this->getDbTable()->delete($where);
	}
}
